package com.vertx.db;

import com.vertx.util.Runner;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.pgclient.PgConnectOptions;
import io.vertx.pgclient.PgPool;
import io.vertx.sqlclient.*;

public class PostgresVerticle extends AbstractVerticle {
	public static void main(String[] args) {

		Runner.runExample(PostgresVerticle.class);

	}

	@Override
	public void start(Promise<Void> startPromise) throws Exception {

		PgConnectOptions connectOptions = new PgConnectOptions()
				.setPort(5432)
				.setHost("localhost")
				.setDatabase("postgres")
				.setUser("walter")
				.setPassword("walter123");
		//String connectionUri = "postgresql://walter:walter123@localhost:5432/postgres";

		// Pool options
		PoolOptions poolOptions = new PoolOptions().setMaxSize(5);

		// Create the pooled client
		PgPool pool = PgPool.pool(vertx, connectOptions, poolOptions);

		// Get a connection from the pool
		//第一步 获取数据库链接
		pool.getConnection(con -> {
			if (con.succeeded()) {
				SqlConnection sqlConnection = con.result();
				//第二步 用获取的数据库链接查询数据库
				sqlConnection.preparedQuery("select * from t_person")
					.execute(rs -> {
						sqlConnection.close();
						//第三步 加工查询出来的数据 并返回给客户端
						if (rs.succeeded()) {
							rs.result().forEach(item -> {
								System.out.println("id : " + item.getInteger(0) + ", first name: " +
										item.getString(1) + ", second name: " + item.getString(2));
							});
						}else {
							System.out.println("fail : " + con.cause().getMessage());
						}
					});
			} else {
				System.out.println("fail : " + con.cause().getMessage());
			}
		});

	}
}
